<?php
namespace ChannelThrift\Service;

use Base\BaseService;
use \Services\AuctionService\InvalidException;

class AssetCenterService extends BaseService {
    Protected $autoCheckFields = false;

    private $dealer_id = null;

    /**
     * 构造
     * @param    int $dealer_id 车商id
     * @return   void
     */
    public function __construct($dealer_id = '') {
        $this->dealer_id = $dealer_id;
        $this->exceptionCode = C('EXCEPTION_CODE');
    }

    /**
     * 冻结车商保证金
     * @param 车商id
     * @param int order_id 使用保证金的拍单id
     * @param $msg 保证金使用描述
     * @param $occur_money 冻结金额
     * @return true/false   成功、失败
     */
    public function freeze($order_id, $occur_money = 2000, $msg = '冻结保证金') {
        if (!is_numeric($order_id) || $order_id <= 0) {
            throw new InvalidException(array('code' => 500055, 'message' => $this->exceptionCode[500055]));
        }
        $dealer_id = $this->dealer_id;

        $DealerBailLogServ = new \ChannelThrift\Service\DealerBailLogService();
        $rows = $DealerBailLogServ->getDealerBailLogList($dealer_id,$order_id);
        if ($rows && count($rows) > 0 && $rows[0]['occur_money'] > 0) {
            //是否已经冻结
            return true;
        }

        //
        $orderServ = new \ChannelThrift\Service\OrderService();
        $row = $orderServ->getFreezeDetail($order_id);
        if (count($row) > 0) {
            $msg = $row[0]['msg'];
        }

        //车商信息
        $dealerServ = new \ChannelThrift\Service\CarDealerService();
        $dealer_info = $dealerServ->getCarDealer($dealer_id);
        if ($dealer_info['bail_amount'] < $occur_money) { //保证金不足
            throw new InvalidException(array('code' => 8000100, 'message' => $this->exceptionCode[8000100]));
        }

        //保证金使用记录
        $remain_amount = ($dealer_info['bail_amount'] - $occur_money);
        $bailLogServ = new \ChannelThrift\Service\DealerBailLogService();
        $log_id = $bailLogServ->insertDealerBailLog($dealer_id,$order_id,2,$msg,$occur_money,$remain_amount);

        //更新车商保证金
        $up_info = array();
        $up_info['freeze_amount'] = ($dealer_info['freeze_amount'] + $occur_money);
        $up_info['bail_amount'] = $remain_amount;
        $eff = $dealerServ->updateCarDealer($dealer_id,$up_info);
        if ($eff <=0) {
            throw new InvalidException(array('code' => 500052, 'message' => $this->exceptionCode[500052]));
        }

        return true;
    }
}
